
from docx.oxml.text.paragraph import CT_P
from docx.oxml.table import CT_Tbl
import re

from docx.text.paragraph import Paragraph
from docx.table import Table
from docx.api import Document


class Charpter(object):
    pass


class ReText(object):
    def __init__(self, pattern, attrname, group='g'):
        self.group = group
        self.pattern = pattern
        self.attrname = attrname

    def search(self, text, obj=None, setsection=True):
        g = re.search(pattern=self.pattern, string=text)
        if g:
            value = g.group(self.group)
            if value != None:
                if obj != None:
                    if hasattr(obj, 'section'):
                        obj.section = self.attrname
                    if hasattr(obj, self.attrname):
                        if hasattr(getattr(obj, self.attrname), 'append'):
                            getattr(obj, self.attrname).append(value)
                        else:
                            setattr(obj, self.attrname, value)
            return value
        return None


class DagangTitle:
    def __init__(self):
        self.sectiondef = [
            ReText('(?P<g>.*)学时', '学时'),
            ReText('(?P<g>.*)学分', '学分'),
            ReText('课程编码(?P<g>.*)', '课程编码'),
            ReText('课程类别(?P<g>.*)', '课程类别'),
        ]
        self.content = []

    def add(self, p):
        self.content.append(p)


class Dagang(object):

    def __init__(self, title=''):
        self.title = title
        self.section = 'title'

        self.line = -1
        self.课程编码 = ''
        self.学时 = ''
        self.学分 = ''
        self.学时学分 = ''
        self.课程类别 = ''
        self.课程性质和教学目的 = []
        self.课程性质 = []
        self.教学目的 = []
        self.section2 = ''
        # self.教学内容 = []
        self.content = []
        self.教学手段与建议 = [],
        self.选用教材 = []
        self.教学内容要求和学时分配 = []
        self.教学手段与建议 = []
        self.考核方式及成绩评定 = []

    def search_set(self, pattern, string1, attrname=None):
        if string1:
            g = re.search(pattern, string1)
            if g and g.group('t') != None:
                value = g.group('t')
                if attrname != None:
                    if hasattr(self, attrname):
                        if isinstance(getattr(self, attrname), str):
                            setattr(self, attrname, value)
                        elif hasattr(getattr(self, attrname), 'append'):
                            getattr(self, attrname).append(value)
                    else:
                        raise AttributeError('属性填写错误')

                return value
        return None

    def dosection_title(self, p):
        课程编码 = self.search_set(r'【课程编码】(?P<t>\w*)',
                               p.text, 't', '课程编码')
        课程类别 = self.search_set(r'【课程类别】(?P<t>\w*)',
                               p.text, 't')
        学时学分 = self.search_set(r'【学时学分】(?P<t>\w*)',
                               p.text, 't')
        学时 = self.search_set(r'【学时学分】(?P<xueshi>\d*)学时，(?P<xuefen>\d*)学分',
                             p.text, 'xueshi')
        学分 = self.search_set(r'【学时学分】(?P<xueshi>\d*)学时，(?P<xuefen>\d*)学分',
                             p.text, 'xuefen')
        if 课程编码:
            self.课程编码 = 课程编码
        if 课程类别:
            self.课程类别 = 课程类别
        if 学时:
            self.学时 = 学时
        if 学分:
            self.学分 = 学分
        if 学时 and 学分:
            self.学时学分 = 学时+'学时'+学分+'学分'
        if 学时学分 and not self.学时学分:
            self.学时学分 = 学时学分

        self.is_next(p.text, '课程性质和教学目的')

    def is_next(self, string1, text, attrname=''):
        findtext = self.search_set(text+r'(?P<t>.*)',
                                   string1, 't')

        if findtext != None:
            print('找到section ', self.line, text)
            self.section = text
            attrname2 = text if not attrname else text
            if findtext != '' and hasattr(self, attrname2):
                if isinstance(getattr(self, attrname2), list):
                    setattr(self, attrname2, [findtext])
                else:
                    setattr(self, attrname2, findtext)

            # else:
            #     setattr(self, probname, [])

    def printtable(self, t):
        print('table', '='*10)
        for i, row in enumerate(t.rows):
            print(self.line, i, *[c.text for c in row.cells])
        print('table', '='*10)

    def dosection_kechengxingzhi(self, p):
        self.search_set(r'^课程性质[:：]+(?P<t>.*)',
                        p.text,  '课程性质')
        教学目的 = self.search_set(r'^教学目的[:：]+(?P<t>.*)',
                               p.text)
        # if 课程性质 != None:
        #     self.section2 = '课程性质'
        #     if 课程性质:
        #         self.课程性质.append(课程性质)
        if 教学目的 != None:
            self.section2 = '教学目的'
            if 教学目的:
                self.教学目的.append(教学目的)

        self.is_next(p.text, '教学内容、要求和学时分配', '教学内容要求和学时分配')

    def add2section(self, p, attrname, next,nextattrname):
        getattr(self,attrname).append(p) 
        self.is_next(p.text, nextattrname)

    def dosection_jiaoxueneirong(self, p, line=-1):
        self.教学内容要求和学时分配.append(p)
        self.is_next(p.text, '选用教材')

    def dosection_xuanyongjiaocao(self, p):
        self.选用教材.append(p)
        self.is_next(p.text, '先修课要求')

    def dosection_xianxiukeyaoqiu(self, p):
        self.选用教材.append(p)
        self.is_next(p.text, '教学手段与建议')

    def dosection_jiaoxueshouduanhejianyi(self, p):
        self.教学手段与建议.append(p)
        self.is_next(p.text, '考核方式及成绩评定')

    def dosection_kaohe(self, p):
        self.考核方式及成绩评定.append(p)

    def dosection_jiaoxueneirongtable(self, t):
        self.教学内容要求和学时分配.append(t)

    def doallparagraph(self, p, line):
        if self.section == 'title':
            self.dosection_title(p)
        elif self.section == '课程性质和教学目的':
            self.dosection_kechengxingzhi(p)
        elif self.section == '教学内容、要求和学时分配':
            self.dosection_jiaoxueneirong(p, line)
        elif self.section == '选用教材':
            self.dosection_xuanyongjiaocao(p)
        elif self.section == '先修课要求':
            self.dosection_xianxiukeyaoqiu(p)
        elif self.section == '教学手段与建议':
            self.dosection_jiaoxueshouduanhejianyi(p)
        elif self.section == '考核方式及成绩评定':
            self.dosection_kaohe(p)

    def fromtable(self, t):
        if self.section == '教学内容、要求和学时分配':  # 有可能有学时
            self.dosection_jiaoxueneirongtable(t)
        else:
            self.printtable(t)
            raise AttributeError('这里有个表格')

    def fromcontent(self):
        for i, p in enumerate(self.content):
            self.line = i
            if isinstance(p, Paragraph):
                self.doallparagraph(p, i)
            elif isinstance(p, Table):
                self.fromtable(p)

    def clean_data(self, printobject=True):
        if not self.title:
            raise AttributeError('标题')
        elif printobject:
            print("名称", self.title)
        if not self.课程编码:
            raise AttributeError('课程编码')
        elif printobject:
            print("课程编码", self.课程编码)
        if not self.学时学分:
            raise AttributeError('学时学分')
        elif printobject:
            print("学时学分", self.学时学分)
        if not self.课程类别:
            raise AttributeError('课程类别')
        elif printobject:
            print("课程类别", self.课程类别)
        if len(self.课程性质) == 0:
            raise AttributeError('课程性质')
        elif printobject:
            print("课程性质", self.课程性质)
        if len(self.教学目的) == 0:
            raise AttributeError('教学目的')
        elif printobject:
            print("教学目的", self.教学目的)

    def save(self):
        if not self.课程编码:
            self.fromcontent()
        self.clean_data()


if __name__ == "__main__":

    doc = Document("d:\\专业选修课.docx")
    body = doc.element.body
    dagang = None
    for i, b1 in enumerate(body.iterchildren()):
        if isinstance(b1, CT_P):
            p = Paragraph(b1, body)
            g = re.search(r'《(?P<title>\w*)》课程教学大纲', p.text)
            title = g.group('title') if g and g.group('title') else ''

            if title:
                if dagang and dagang.title:
                    dagang.save()
                    dagang = None
                    break
                dagang = Dagang(title)
            if dagang:
                dagang.content.append(p)
            # continue
        elif isinstance(b1, CT_Tbl):
            t = Table(b1, body)
            # print(i, 'table', len(t.rows), len(t.columns))
            # break
            if dagang:
                dagang.content.append(t)
        else:
            print(i, '未处理类型'*5, type(b1))
            pass

    if dagang:
        dagang.save()
